#include "pack.h"
#include "myClient.h"

Pack::Pack()
{

}

void Pack::setType(Type type)
{
    this->type = type;
}

void Pack::setErr(Err err)
{
    this->err = err;
}

Type Pack::getType()
{
    return type;
}

Err Pack::getErr()
{
    return err;
}

//将数据添加到协议包
void Pack::append(const QString &str)
{
    const char* ptr = str.toLocal8Bit().data();
    short len = strlen(ptr);
    *(short*)(buf+count) = len;
    count += 2;
    memcpy(buf+count,ptr,len);
    count += len;
    pack_size = 12 + count;
}

void Pack::append(const char *data, int size)
{
    memset(buf,0,4096);
    memcpy(buf,data,size);
    count = size;
    pack_size = count+12;
}

//解析协议包
QStringList Pack::analysis()
{
    QStringList list;
    int read_size = 0;
    while(1)
    {
        short size = *(short*)(buf+read_size);
        if(size == 0)
        {
            break;
        }
        read_size += 2;
        char temp[size + 1];
        memset(temp,0,size+1);
        memcpy(temp,buf+read_size,size);
        QString data = QString::fromLocal8Bit(temp);
        list<<temp;
        read_size += size;
    }
    memset(buf,0,4096);
    count = 0;
    pack_size = 12;
    return list;
}

Pack &Pack::operator<<(const QString &data)
{
    append(data);
    return *this;
}

void Pack::operator>>(QTcpSocket *client)
{
    client->write((char*)this,pack_size);
}

void Pack::operator>>(myClient *client)
{
    client->write((char*)this,pack_size);
}

QByteArray Pack::getByteArray(int size)
{
    return QByteArray::fromRawData(buf,size);
}
